<template>
  <div class="hospital-department-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <el-button type="primary" size="small" @click="handleBack">返回</el-button>
      <h2>二级分类</h2>
    </div>

    <!-- 科室列表 -->
    <div class="card-container" style="overflow-x: auto;">
      <div class="table-header">
        <h3>科室列表</h3>
        <div class="header-actions">
          <el-button type="primary" :icon="Plus" @click="handleAddDepartment">
            新增科室
          </el-button>
        </div>
      </div>

      <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        row-key="id"
        @selection-change="handleSelectionChange"
        border
      >
        <el-table-column type="selection" width="55" />        
        <el-table-column prop="name" label="科室名称" min-width="180" />
        <el-table-column prop="level" label="级别" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '显示' ? 'success' : 'info'">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="备注" min-width="150" />
        <el-table-column prop="uploader" label="上传人" width="120" />
        <el-table-column prop="uploadTime" label="添加时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.uploadTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="{ row }">
            <el-space wrap>
              <el-button
                type="primary"
                size="small"
                @click="handleAddSubDepartment(row)"
              >
                新增下级
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleViewSubDepartment(row)"
              >
                查看下级
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="handleEditDepartment(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                :loading="deleteLoading && currentDeleteId === row.id"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作 -->
      <div class="batch-operations" v-if="selectedRows.length > 0">
        <el-checkbox v-model="selectAll" @change="handleSelectAllChange">全选</el-checkbox>
        <span>已选择 {{ selectedRows.length }} 项</span>
        <el-button
          type="danger"
          :loading="batchDeleteLoading"
          @click="handleBatchDelete"
        >
          批量删除
        </el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { departmentApi } from '@/api/index'
import type { DepartmentItem, DepartmentSearchParams } from '@/api/index'

/**
 * 智慧医疗系统 - 医院科室管理页面
 * 功能：管理医院的科室信息，包括科室的增删改查、医生管理等
 */

// 接口类型定义
interface DepartmentItem {
  id: number
  name: string
  level: string
  status: string
  description?: string
  doctorCount: number
  hospitalId: number
  parentId?: number
  uploader: string
  uploadTime: string
}

interface SearchForm {
  name: string
  level: string
  status: string
}

// 响应式数据
const loading = ref(false)
const selectedRows = ref<DepartmentItem[]>([])
// 删除相关状态
const deleteLoading = ref(false)
const batchDeleteLoading = ref(false)
const currentDeleteId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  level: '',
  status: ''
})

// 表格数据
const tableData = ref<DepartmentItem[]>([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 路由相关
const route = useRoute()
const router = useRouter()
const hospitalId = Number(route.params.hospitalId)

// 生命周期
onMounted(() => {
  loadData()
})

// 方法
/**
 * 加载科室数据
 * @param resetPagination 是否重置分页
 */
const loadData = async (resetPagination = false) => {
  if (resetPagination) {
    pagination.currentPage = 1
  }

  loading.value = true
  try {
    const params: DepartmentSearchParams = {
      hospitalId,
      name: searchForm.name,
      level: searchForm.level,
      status: searchForm.status,
      currentPage: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const response = await departmentApi.getList(params)

    if (response.code === 200) {
      const data = response.data
      tableData.value = data.items
      pagination.total = data.totalCount
    } else {
      ElMessage.error('获取科室数据失败')
    }
  } catch (error) {
    console.error('加载科室数据出错:', error)
    ElMessage.error('加载科室数据失败，请重试')
  } finally {
    loading.value = false
  }
}

/**
 * 查看科室详情
 */
const handleViewDepartment = (row: DepartmentItem) => {
  router.push({
    path: `/content/hospital/${hospitalId}/department/detail/${row.id}`
  })
}

/**
 * 新增科室
 */
const handleAddDepartment = () => {
  router.push({
    path: `/content/hospital/${hospitalId}/department/add`
  })
}

/**
 * 新增下级科室
 */
const handleAddSubDepartment = (row: DepartmentItem) => {
  router.push({
    path: `/content/hospital/${hospitalId}/department/add`,
    query: { parentId: row.id }
  })
}

/**
 * 编辑科室
 */
const handleEditDepartment = (row: DepartmentItem) => {
  router.push({
    path: `/content/hospital/${hospitalId}/department/edit/${row.id}`
  })
}

/**
 * 删除科室
 */
const handleDelete = async (row: DepartmentItem) => {
  ElMessageBox.confirm('确定要删除该科室吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      deleteLoading.value = true
      currentDeleteId.value = row.id
      try {
        const response = await departmentApi.delete(row.id)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          loadData()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        console.error('删除科室出错:', error)
        ElMessage.error('删除失败，请重试')
      } finally {
        deleteLoading.value = false
        currentDeleteId.value = null
      }
    })
    .catch(() => {
      // 取消删除
    })
}

/**
 * 批量删除
 */
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的科室')
    return
  }

  ElMessageBox.confirm('确定要删除选中的科室吗？', '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      batchDeleteLoading.value = true
      const ids = selectedRows.value.map(row => row.id)
      try {
        const response = await departmentApi.batchDelete(ids)
        if (response.code === 200) {
          ElMessage.success('删除成功')
          selectedRows.value = []
          loadData()
        } else {
          ElMessage.error('删除失败')
        }
      } catch (error) {
        console.error('批量删除科室出错:', error)
        ElMessage.error('删除失败，请重试')
      } finally {
        batchDeleteLoading.value = false
      }
    })
    .catch(() => {
      // 取消删除
    })
}

/**
 * 搜索
 */
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

/**
 * 重置搜索
 */
const handleReset = () => {
  searchForm.name = ''
  searchForm.level = ''
  searchForm.status = ''
  pagination.currentPage = 1
  loadData()
}

/**
 * 分页大小改变
 */
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  loadData()
}

/**
 * 当前页改变
 */
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
  loadData()
}

/**
 * 选择行改变
 */
const handleSelectionChange = (rows: DepartmentItem[]) => {
  selectedRows.value = rows
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

/**
 * 返回上一页
 */
const handleBack = () => {
  router.back();
}

/**
 * 查看下级科室
 */
const handleViewSubDepartment = (row: DepartmentItem) => {
  // 这里实现查看下级科室的逻辑
  ElMessage.info('查看下级科室功能待实现');
}

/**
 * 全选改变
 */
const selectAll = ref(false);
const handleSelectAllChange = (value: boolean) => {
  if (value) {
    // 实现全选逻辑
  } else {
    selectedRows.value = [];
  }
}
</script>

<style lang="scss" scoped>
.hospital-department-management {
  padding: 20px;

  .page-header {
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: $text-color-primary;
    }
  }

  .card-container {
    background-color: $bg-color;
    border-radius: 4px;
    padding: 16px;
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e6e6e6;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .batch-operations {
    margin-top: 16px;
    padding: 12px;
    background-color: $bg-color;
    border-radius: 4px;
    display: flex;
    align-items: center;

    span {
      margin: 0 16px;
    }
  }
}
</style>